﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TcpSyncIMServer;

namespace TcpSyncIM
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public bool appRun = true;
        private Listener lis;
        private Sender sen;
        string netIp;
        string chatTo;

        public void AddMessage(object sender, AddMessageEventArgs addMessageEventArgs) {
            string message = addMessageEventArgs.Message;
            string appendText;
            string[] sep = message.Split(">");
            appendText = sep[0]+">:"+System.DateTime.Now.ToString()+Environment.NewLine+sep[1]+Environment.NewLine;
            int txtGetMsgLength = this.richTextBox1.Text.Length;
            this.richTextBox1.AppendText(appendText);
            this.richTextBox1.Select(txtGetMsgLength, appendText.Length - Environment.NewLine.Length * 2 - sep[1].Length);
            this.richTextBox1.SelectionColor = Color.Red;
            this.richTextBox1.ScrollToCaret();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            netIp = GetNetId();
            this.label1.Text = "本机ip:" + GetMyIpAddress();
            start_listen();
        }

        private void start_listen()
        {
            try
            {
                if (lis.lisenerRun == true)
                {
                    lis.lisenerRun = false;
                    lis.Stop();
                }
            }
            catch
            {

            }
            finally {
                lis = new Listener();
                lis.OnAddMessage += new EventHandler<AddMessageEventArgs>(this.AddMessage);
                lis.StartLisener();
            }
        }

        string GetNetId() {
            string netId;
            string ip = GetMyIpAddress();
            netId = ip.Substring(0, ip.LastIndexOf(".") + 1);
            return netId;
        }

        private string GetMyIpAddress()
        {
            IPAddress iPAddress = new IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address);
            return iPAddress.ToString();
        }
        /// <summary>
        /// 连接服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Trim() == "")
            {
                MessageBox.Show("请输入主机号");
                return;
            }
            else
            {
                try
                {
                    chatTo = textBox1.Text;
                    TcpClient tcpClient=new TcpClient(textBox1.Text,5656);
                    NetworkStream networkStream = tcpClient.GetStream();
                    Byte[] bytes = System.Text.UTF8Encoding.UTF8.GetBytes("1");
                    networkStream.Write(bytes, 0, bytes.Length);
                    networkStream.Close();
                    tcpClient.Close();
                    this.toolStripStatusLabel1.Text = "当前状态:已连接到服务器";
                }
                catch (SocketException){
                    MessageBox.Show("目标主机没有启动监听", "系统提示");
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                sen = new Sender(chatTo);
                sen.Send("0");
                lis.lisenerRun = false;
                lis.Stop(); ;
                this.toolStripStatusLabel1.Text = "当前状态:与服务器断开连接";
            }
            catch { 
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            if (richTextBox2.Text.Trim() == "")
            {
                MessageBox.Show("请选择目标主机");
                return;
            }
            else if (this.richTextBox2.Text.Trim() == "")
            {
                MessageBox.Show("消息内容不为空", "错误");
                this.label1.Focus();
                return;
            }
            else {
                try
                {
                  sen=new Sender(chatTo);
                    sen.Send(richTextBox2.Text);
                    string appendText;
                    appendText = "Me;" + System.DateTime.Now.ToString() + Environment.NewLine + richTextBox2.Text + Environment.NewLine;
                    int txtGetMsgLength = this.richTextBox1.Text.Length;
                    this.richTextBox1.AppendText(appendText);
                    this.richTextBox1.Select(txtGetMsgLength, appendText.Length - Environment.NewLine.Length * 2 - richTextBox2.Text.Length);
                    this.richTextBox1.SelectionColor = Color.Blue;
                    this.richTextBox1.ScrollToCaret();
                }
                catch {
                
                }
                this.textBox1.Text = "";
                this.textBox1.Focus();
            }
        }
    }
}
